package com.lt.bigevent.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.lt.bigevent.dto.UserRegisterDto;
import com.lt.bigevent.entity.User;
import com.lt.bigevent.service.UserService;
import com.lt.bigevent.util.JwtUtil;
import com.lt.bigevent.util.Md5Util;
import com.lt.bigevent.util.ThreadLocalUtil;
import com.lt.bigevent.vo.Result;
import org.hibernate.validator.constraints.URL;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.Pattern;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author : litie
 * @date : 2023/11/9 11:43
 */
@RestController
@RequestMapping("/user")
@Validated
public class UserController {

    @Resource
    private UserService userService;
    /**
     * 用户注册接口
     * @param userRegisterDto u
     * @return re
     */
    @PostMapping("/register1")
    public Result<String> userRegister1(@Valid @RequestBody UserRegisterDto userRegisterDto){
        String userName = userRegisterDto.getUserName();
        String password = userRegisterDto.getPassword();
        //判断用户名或密码是否为空
        if(!StringUtils.hasText(userName) || !StringUtils.hasText(password)){
            return Result.error("用户名或密码不能为空！");
        }
        //查询该用户名是否存在
        LambdaUpdateWrapper<User> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(User::getUsername,userName);
        User one = userService.getOne(wrapper);
        if(Objects.nonNull(one)){
            return Result.error("用户名已存在！");
        }
        //密码md5加密后进行注册
        String md5String = Md5Util.getMD5String(password);
        User user = new User();
        user.setUsername(userName);
        user.setPassword(md5String);
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        userService.save(user);
        return Result.success();
    }

    /**
     * 用户注册接口
     * @param userName 用户名
     * @param password 密码
     * @return re
     */
    @PostMapping("/register")
    public Result<String> userRegister(@Pattern(regexp = "^\\S{5,16}$") String userName, @Pattern(regexp = "^\\S{5,16}$") String password){

        //查询该用户名是否存在
        LambdaUpdateWrapper<User> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(User::getUsername,userName);
        User one = userService.getOne(wrapper);
        if(Objects.nonNull(one)){
            return Result.error("用户名已存在！");
        }
        //密码md5加密后进行注册
        String md5String = Md5Util.getMD5String(password);
        User user = new User();
        user.setUsername(userName);
        user.setPassword(md5String);
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        userService.save(user);
        return Result.success();
    }

    /**
     * 用户登录接口
     * @param userName 用户名
     * @param password 密码
     * @return re
     */
    @PostMapping("/login")
    public Result<String> userLogin(@Pattern(regexp = "^\\S{5,16}$") String userName, @Pattern(regexp = "^\\S{5,16}$") String password){
        //查询该用户名是否存在
        LambdaUpdateWrapper<User> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(User::getUsername,userName);
        User one = userService.getOne(wrapper);
        if(Objects.isNull(one)){
            return Result.error("用户名不存在！");
        }
        //密码md5加密后进行比较
        String md5String = Md5Util.getMD5String(password);
        if (!md5String.equals(one.getPassword())) {
            return Result.error("密码错误！");
        }
        //根据用户id和用户名生成token返回给前端
        Map<String,Object> claims = new HashMap<>();
        claims.put("userId",one.getId());
        claims.put("userName",one.getUsername());
        String token = JwtUtil.genToken(claims);
        return Result.success(token);
    }

    @GetMapping("/userInfo")
    public Result<User> userInfo() {
        //根据用户名查询用户
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("userName");
        User one = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getUsername, username));
        return Result.success(one);
    }

    @PostMapping("/update")
    public Result<String> update(@RequestBody @Validated User user) {
        //根据用户名查询用户
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("userName");
        User one = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getUsername, username));
        if(user.getId().equals(one.getId())){
            LambdaUpdateWrapper<User> wrapper = new LambdaUpdateWrapper<>();
            wrapper.set(User::getNickname,user.getNickname());
            wrapper.set(User::getEmail,user.getEmail());
            wrapper.set(User::getUpdateTime,new Date());
            wrapper.eq(User::getId,user.getId());
            userService.update(wrapper);
            return Result.success();
        }else {
            return Result.error("用户名不符合,更新失败！");
        }

    }

    @PatchMapping("/updateAvatar")
    public Result<String> updateAvatar(@RequestParam @URL String avatarUrl) {
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("userId");
        LambdaUpdateWrapper<User> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(User::getUserPic,avatarUrl).set(User::getUpdateTime,new Date());
        wrapper.eq(User::getId,id);
        userService.update(wrapper);
        return Result.success();
    }

    @PatchMapping("/updatePwd")
    public Result<String> updatePwd(@RequestBody Map<String, String> params,@RequestHeader("Authorization") String token) {
        //1.校验参数
        String oldPwd = params.get("old_pwd");
        String newPwd = params.get("new_pwd");
        String rePwd = params.get("re_pwd");

        if (!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd)) {
            return Result.error("缺少必要的参数");
        }

        //原密码是否正确
        //调用userService根据用户名拿到原密码,再和old_pwd比对
        Map<String,Object> map = ThreadLocalUtil.get();
        String userName = (String) map.get("userName");
        LambdaUpdateWrapper<User> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(User::getUsername,userName);
        User loginUser = userService.getOne(wrapper);
        if (!loginUser.getPassword().equals(Md5Util.getMD5String(oldPwd))){
            return Result.error("原密码填写不正确");
        }

        //newPwd和rePwd是否一样
        if (!rePwd.equals(newPwd)){
            return Result.error("两次填写的新密码不一样");
        }

        Integer id = (Integer) map.get("userId");
        //2.调用service完成密码更新
        LambdaUpdateWrapper<User> wrapper1 = new LambdaUpdateWrapper<>();
        String md5String = Md5Util.getMD5String(newPwd);
        wrapper1.set(User::getPassword,md5String).set(User::getUpdateTime,new Date());
        wrapper1.eq(User::getId,id);
        userService.update(wrapper1);
//        //删除redis中对应的token
//        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
//        operations.getOperations().delete(token);
        return Result.success();
    }
}
